<template>
  <div class="container">
    <OrderBar :username="userInfo.userName" :order="serviceNo"></OrderBar>
    <div class="content">
      <van-form ref="form" class="form">
        <van-field
          v-model="form.workDay"
          name="workDay"
          clickable
          required
          :rules="rules.workDay"
          readonly
          label="工作日期"
          placeholder="点击选择日期"
          @click="openCalendar('workDay')"
        />
        <van-field
          v-model="form.workBeginDate"
          name="workBeginDate"
          clickable
          required
          readonly
          :rules="rules.workBeginDate"
          label="开始时间"
          placeholder="点击选择时间"
          @click="openDatetimePicker('workBeginDate')"
        />
        <van-field
          v-model="form.workEndDate"
          name="workEndDate"
          clickable
          required
          readonly
          :rules="rules.workEndDate"
          label="结束时间"
          placeholder="点击选择时间"
          @click="openDatetimePicker('workEndDate')"
        />
        <van-field
          v-model="form.coordinateUser"
          name="coordinateUser"
          rows="1"
          label="配合人员"
          type="text"
          placeholder="请输入配合人员"
        />

        <van-field
          v-model="form.workContent"
          name="workContent"
          rows="1"
          required
          :rules="rules.workContent"
          autosize
          label="工作内容"
          type="textarea"
          placeholder="请输入工作内容"
          maxlength="100"
          show-word-limit
        />

        <van-field name="checkboxGroup" label="费用明细" />
        <van-field name="checkboxGroup">
          <template #input>
            <van-checkbox-group
              v-model="form.mealList"
              direction="horizontal"
            >
              <van-checkbox
                v-for="(v,i) in options.mealList"
                :key="i"
                :name="v.value"
                shape="square"
                @click="costDetailsChange(v, 'mealList')"
              >
                {{ v.label }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <div
          v-for="(v, i) in form.mealListForm"
          v-show="form.mealList.includes(v.feePurpose)"
          :key="v.feePurpose"
          class="cost-details-list van-cell"
        >
          <van-field
            v-model="v.feeNum"
            type="number"
            :name="`mealListForm.${i}.feeNum`"
            label="数量"
            required
            :rules="rules.required"
            placeholder="请输入数量"
            label-width="40px"
          />
          <van-field
            v-model="v.price"
            type="number"
            label="价格"
            required
            :disabled="!!mealMoneyMap[v.feePurpose]"
            :name="`mealListForm.${i}.price`"
            :rules="rules.required"
            placeholder="请输入价格"
            label-width="40px"
          />
        </div>

        <van-field name="checkboxGroup">
          <template #input>
            <van-checkbox-group
              v-model="form.costList"
              direction="horizontal"
            >
              <van-checkbox
                v-for="(v,i) in options.costList"
                :key="i"
                :name="v.value"
                shape="square"
                @click="costDetailsChange(v, 'costList')"
              >
                {{ v.label }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <div
          v-for="(v,i) in form.costListForm"
          v-show="form.costList.includes(v.feePurpose)"
          :key="v.feePurpose"
          class="cost-details-list-box van-cell"
        >
          <div class="cost-details-list van-cell">
            <van-field
              v-model="v.feeNum"
              type="number"
              label="数量"
              :name="`costListForm.${i}.feeNum`"
              required
              :rules="rules.required"
              placeholder="请输入数量"
              label-width="40px"
            />
            <van-field
              v-model="v.price"
              type="number"
              label="价格"
              :name="`costListForm.${i}.price`"
              required
              :rules="rules.required"
              placeholder="请输入价格"
              label-width="40px"
            />
          </div>
          <div class="van-cell">
            <van-field
              v-model="v.feeDesc"
              label="花费内容"
              rows="1"
              autosize
              required
              :name="`costListForm.${i}.feeDesc`"
              :rules="rules.required"
              type="textarea"
              maxlength="500"
              show-word-limit
              placeholder="花费内容"
            />
          </div>

        </div>

        <van-cell title="其他费用">
          <van-icon
            name="add-o"
            color="blue"
            size="18"
            @click="addOtherCost"
          />
        </van-cell>

        <div v-for="(v, i) in form.otherCost" :key="v.time" class="otherCost van-cell">
          <div class="left">
            <div v-if="false" class="van-cell">
              <van-field
                v-model="v.workDay"
                required
                :name="`otherCost.${i}.workDay`"
                :rules="rules.required"
                clickable
                readonly
                label=""
                placeholder="费用日期"
                @click="openCalendar('workDay', v)"
              />
            </div>
            <div class="van-cell">
              <van-field
                v-model="v.feePurposeName"
                :name="`otherCost.${i}.feePurpose`"
                :rules="rules.required"
                required
                readonly
                clickable
                placeholder="费用属性"
                @click="openPicker('feePurpose', v, changeCost)"
              />
              <van-field
                v-model="v.feeNum"
                type="number"
                required
                :name="`otherCost.${i}.feeNum`"
                :rules="rules.required"
                placeholder="数量"
                label-width="40px"
              />
              <van-field
                v-model="v.price"
                type="number"
                required
                :disabled="!!moneyMap[v.feePurpose]"
                :name="`otherCost.${i}.price`"
                :rules="rules.required"
                placeholder="价格"
                label-width="40px"
              />
            </div>
            <div>
              <van-field
                v-model="v.feeDesc"
                rows="1"
                autosize
                required
                :name="`otherCost.${i}.feeDesc`"
                :rules="rules.required"
                type="textarea"
                maxlength="500"
                show-word-limit
                placeholder="花费内容"
              />
            </div>
          </div>
          <div class="right">
            <van-icon
              name="close"
              color="red"
              size="18"
              @click="removeOtherCost(i)"
            />
          </div>

        </div>

        <van-popup
          v-model="showDatetimePicker"
          position="bottom"
        >
          <van-datetime-picker
            v-model="currentDate"
            type="datetime"
            title="选择时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmDatetimePicker"
            @cancel="onCancelDatetimePicker"
          />
        </van-popup>

        <van-calendar
          v-model="showCalendar"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirmCalendar"
        />

        <van-popup
          v-model="showPicker"
          position="bottom"
        >
          <van-picker
            show-toolbar
            :columns="currentOptions"
            value-key="label"
            @confirm="onConfirmPicker"
            @cancel="showPicker = false"
          >
            <van-search
              v-if="currentOptionsCache.length>showSearchMaxOptionsLength"
              slot="title"
              v-model="pickerKeyword"
              placeholder="快速搜索"
              shape="round"
              @input="filterCurrentOptions"
            />
          </van-picker>
        </van-popup>

        <div class="btns">
          <van-button
            type="warning"
            size="small"
            icon="checked"
            @click="submit('/saleService/saveOrUpdateWorkLog')"
          >提交
          </van-button>
          <van-button
            type="danger"
            size="small"
            icon="clear"
            @click="close"
          >关闭
          </van-button>
        </div>

      </van-form>
    </div>

  </div>
</template>

<script>
import OrderBar from '../../components/OrderBar'
import { form, userInfo } from '../../assets/utils/mixin'
import { urlParams } from '@/assets/utils'

export default {
  components: { OrderBar },
  mixins: [ userInfo, form ],
  data() {
    const ruleKeys = [
      'workDay',
      'workBeginDate',
      'workEndDate',
      'coordinateUser',
      'workContent',
      'required',
    ]
    const rules = {}
    ruleKeys.forEach(key => rules[key] = [ { required: true } ])

    return {
      serviceNo: urlParams.get('serviceNo'),
      workLogId: urlParams.get('workLogId'),
      form: {
        saleServiceId: urlParams.get('saleServiceId'),
        workDay: '',
        workBeginDate: '',
        workEndDate: '',
        coordinateUser: '',
        workContent: '',

        mealList: [], // 餐费
        costList: [], // 住宿、车费

        mealListForm: [], // 餐费 表单
        costListForm: [], // 住宿、车费 表达

        otherCost: [],
      },

      options: {
        mealList: [],
        costList: [],
        feePurpose: [],
      },

      rules,
      moneyMap: {
        '101_101': 300,
        '103_105':100,

      },
      mealMoneyMap : {
        '100_101': 8,
        '100_102': 20,
        '100_103': 20,
        '100_107': 12,
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.init()
  },
  mounted() {
  },
  methods: {
    async init() {
      this.getUserInfo()
      await this.getCostOptions()
      // this.getOtherCostOptions()
      this.getWorkDetail()
      // this.getfeePurposeOptions()
    },

    async getWorkDetail() {
      if (!this.workLogId) return
      const res = await this.server.get('/saleService/getSaleServiceWorkLogBySaleServiceIdOrWorkLogId', {
        workLogId: this.workLogId,
        saleServiceId: this.form.saleServiceId,
      })
      if (res.code === '0') {
        Object.assign(this.form, res.object)
        // 处理回显数据
        for (const item of res.object.fees) {
          if ([ '100_104', '100_105' ].includes(item.feePurpose)) {
            // 车费，住宿费
            this.form.costList.push(item.feePurpose)
            const obj = this.form.costListForm.find(e => e.feePurpose === item.feePurpose)
            if (obj) Object.assign(obj, item)
          } else if ([ '100_101', '100_102', '100_103', '100_107' ].includes(item.feePurpose)) {
            // 餐费
            this.form.mealList.push(item.feePurpose)
            const obj = this.form.mealListForm.find(e => e.feePurpose === item.feePurpose)
            if (obj) Object.assign(obj, item)
          } else {
            // 其他费用
            this.addOtherCost(item)
          }
        }
      }
    },

    async getOptionsType(parentId) {
      const res = await this.server.get('/saleService/findNoteSubFeeTypes', { parentId })
      return res
    },

    // 费用明细 选项
    async getCostOptions() {
      const res = await this.server.get('/saleService/findNoteAllFeePurpose')
      if (res.code === '0') {
        const mealList = []
        const costList = []
        const feePurposeList = []
        for (const val of res.object) {
          if (val.defaultShow && val.defaultRemark) {
            costList.push({ label: val.feePurposeName, value: val.feePurpose })
          } else if (val.defaultShow && !val.defaultRemark) {
            mealList.push({ label: val.feePurposeName, value: val.feePurpose })
          } else if (!val.defaultShow && !val.defaultRemark) {
            feePurposeList.push({ label: val.feePurposeName, value: val.feePurpose })
          }
        }

        this.options.mealList = mealList
        this.options.costList = costList
        this.options.feePurpose = feePurposeList

        this.form.mealListForm = mealList.map(e => ({
          saleServiceId: this.form.saleServiceId, feeNum: null, price: this.mealMoneyMap[e.value],
          feePurpose: e.value, feePurposeName: e.label, feeDesc: '',
        }))
        this.form.costListForm = costList.map(e => ({
          saleServiceId: this.form.saleServiceId, feeNum: null, price: null,
          feePurpose: e.value, feePurposeName: e.label, feeDesc: '',
        }))
      }
    },
    // 其他费用 - 费用属性
    async getOtherCostOptions() {
      Promise.all([
        this.getOptionsType('105'),
        this.getOptionsType('106'),
      ]).then(res => {
        this.options.feePurpose = res.flat().map(e => ({ label: e.name, value: e.value }))
      })
    },

    // 查询处理方式的下拉字典
    async getDict(parentId) {
      const res = await this.server.get('/saleService/findReportAllFeePurpose', {
        parentId,
      })
      return res
    },

    // 其他费用 - 费用属性
    async getfeePurposeOptions() {
      const res = await this.getDict('103')
      if (res.code === '0') {
        this.options.feePurpose = res.object.map(e => ({
          label: e.feePurposeName, value: e.feePurpose,
        }))
      }
    },

    changeCost(form) {
      form.price = this.moneyMap[form.feePurpose]
    },

    costDetailsChange(data, key) {
      if (!this.form[key].includes(data.value)) {
        // 取消勾选清空数据
        const obj = this.form[key + 'Form'].find(e => e.feePurpose === data.value)
        obj.feeNum = null
        obj.price = null
        obj.feeDesc = null

        // 删除校验
        const index = this.form[key + 'Form'].findIndex(e => e.feePurpose === data.value)
        delete this.rules[`${key}Form.${index}.feeNum`]
        delete this.rules[`${key}Form.${index}.price`]
        if (key === 'costList') {
          delete this.rules[`${key}Form.${index}.feeDesc`]
        }
      } else {
        // 勾选时 增加校验
        const index = this.form[key + 'Form'].findIndex(e => e.feePurpose === data.value)
        this.rules[`${key}Form.${index}.feeNum`] = this.rules.required
        this.rules[`${key}Form.${index}.price`] = this.rules.required
        if (key === 'costList') this.rules[`${key}Form.${index}.feeDesc`] = this.rules.required
      }
    },

    addOtherCost(item = {}) {
      this.form.otherCost.push({
        saleServiceId: this.form.saleServiceId,
        feePurpose: item.feePurpose || '',
        feePurposeName: item.feePurposeName || '',
        feeDesc: item.feeDesc || '',
        workDay: item.workDay || null,
        feeNum: item.feeNum || null,
        price: item.price || null,
        time: new Date().getTime(),
      })
    },

    removeOtherCost(index) {
      this.form.otherCost.splice(index, 1)
    },

    async submit(url) {
      if (this.loadingSubmit) return
      this.form.otherCost.forEach((e, i) => {
        this.rules[`otherCost.${i}.workDay`] = this.rules.required
        this.rules[`otherCost.${i}.feeNum`] = this.rules.required
        this.rules[`otherCost.${i}.price`] = this.rules.required
        this.rules[`otherCost.${i}.feeDesc`] = this.rules.required
      })

      const bol = await this.validate()
      if (!bol) return this.$toast('请填写表单')
      // 组装数据
      this.form.fees = [
        ...this.form.mealListForm.filter(e => this.form.mealList.includes(e.feePurpose)),
        ...this.form.costListForm.filter(e => this.form.costList.includes(e.feePurpose)),
        ...this.form.otherCost,
      ]
      this.loadingSubmit = true
      this.$toast('提交中，请勿重复提交！')
      const res = await this.server.post(url, this.form)
      if (res.code === '0') {
        this.$toast({ message: '提交成功', duration: 1000, onClose: () => this.close() })
      } else {
        this.$toast(res.msg || res.message)
        this.loadingSubmit = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import "../../assets/var";

.container {
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  position: relative;

  > div {
    width: 100%;

  }

  .content {
    position: relative;
    flex: 1;
    background: #f8f8f8;

    .form {
      margin-bottom: 100px;
      width: 100%;
      min-height: calc(100% - 56px);

      .cost-details-list-box {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding: 0;

        > .van-cell {
          padding: 0;
        }
      }

      .cost-details-list {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0;

        .van-cell {
          &::after {
            display: none;
          }
        }
      }

      .otherCost {
        background: #fff;
        display: flex;
        justify-content: center;
        align-items: flex-start;
        padding: 0;

        .left {
          flex: 1;

          > .van-cell {
            padding: 0;
          }
        }

        .right {
          width: 40px;
          height: 80px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }

      .btns {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        margin-bottom: 30px;
        .safe-margin();
      }
    }
  }

}
</style>
